package com.hisense.ovcloud.commons.configs.redis;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.lettuce.core.ClientOptions;
import io.lettuce.core.cluster.ClusterClientOptions;
import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.session.data.redis.config.ConfigureRedisAction;

import java.time.Duration;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Configuration
@Slf4j
@Lazy
@ConditionalOnClass(ConfigureRedisAction.class)
public class LettuceConfig {
    @Value("${spring.redis.commandTimeoutSecond:5}")
    private int commandTimeout;

    @Value("${spring.redis.refreshTriggersTimeoutSecond:10}")
    private int refreshTriggersTimeoutSecond;

    @Value("${spring.redis.periodicRefreshSecond:10}")
    private int periodicRefreshSecond;

    @Value("${spring.redis.lettuce.pool.testOnBorrow:true}")
    private boolean testOnBorrow;

    @Value("${spring.redis.lettuce.pool.enableAllAdaptiveRefreshTriggers:true}")
    private boolean enableAllAdaptiveRefreshTriggers;

    @Value("${spring.redis.lettuce.pool.validateConnection:false}")
    private boolean validateConnection;

    @Value("${spring.redis.lettuce.pool.testOnCreate:true}")
    private boolean testOnCreate;

    @Value("${spring.redis.lettuce.pool.testOnReturn:false}")
    private boolean testOnReturn;

    @Value("${spring.redis.lettuce.pool.setShareNativeConnection:true}")
    private boolean setShareNativeConnection;

    @Value("${spring.redis.lettuce.pool.resetConnection:false}")
    private boolean resetConnection;

    private final RedisProperties redisProperties;

    public LettuceConfig(RedisProperties redisProperties) {
        this.redisProperties = redisProperties;
    }

    @Bean
    @SuppressWarnings("all")
    public GenericObjectPoolConfig<?> genericObjectPoolConfig(RedisProperties.Pool properties) {
        GenericObjectPoolConfig<?> config = new GenericObjectPoolConfig<>();
        config.setMaxTotal(properties.getMaxActive());
        config.setMaxIdle(properties.getMaxIdle());
        config.setMinIdle(properties.getMinIdle());
        if (null != properties.getTimeBetweenEvictionRuns()) {
            config.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRuns().toMillis());
        }
        if (null != properties.getMaxWait()) {
            config.setMaxWaitMillis(properties.getMaxWait().toMillis());
        }
        config.setTestOnBorrow(testOnBorrow);
        config.setTestOnCreate(testOnCreate);
        config.setTestOnReturn(testOnReturn);
        return config;
    }

    @Bean(destroyMethod = "destroy")
    public LettuceConnectionFactory lettuceConnectionFactory() {
        //开启 自适应集群拓扑刷新和周期拓扑刷新
        ClusterTopologyRefreshOptions clusterTopologyRefreshOptions = ClusterTopologyRefreshOptions.builder()
                // 开启全部自适应刷新
                .enableAllAdaptiveRefreshTriggers() // 开启自适应刷新,自适应刷新不开启,Redis集群变更时将会导致连接异常
                // 自适应刷新超时时间(默认30秒)
                .adaptiveRefreshTriggersTimeout(Duration.ofSeconds(refreshTriggersTimeoutSecond)) //默认关闭开启后时间为30秒
                // 开周期刷新
                .enablePeriodicRefresh(Duration.ofSeconds(periodicRefreshSecond))  // 默认关闭开启后时间为60秒 ClusterTopologyRefreshOptions.DEFAULT_REFRESH_PERIOD 60  .enablePeriodicRefresh(Duration.ofSeconds(2)) = .enablePeriodicRefresh().refreshPeriod(Duration.ofSeconds(2))
                .build();

        ClientOptions clientOptions = enableAllAdaptiveRefreshTriggers ? ClusterClientOptions.builder()
                .topologyRefreshOptions(clusterTopologyRefreshOptions)
                .build() : ClusterClientOptions.builder()
                .build();

        LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
                .poolConfig(genericObjectPoolConfig(redisProperties.getLettuce().getPool()))
                //.readFrom(ReadFrom.MASTER_PREFERRED)
                .clientOptions(clientOptions)
                .commandTimeout(Duration.ofSeconds(commandTimeout)) //默认RedisURI.DEFAULT_TIMEOUT 60
                .build();

        List<String> clusterNodes = new ArrayList<>();
        try{
            clusterNodes = redisProperties.getCluster().getNodes();
        }catch (Exception e){
            log.info("didn't fetch redis cluster node, use default instead.");
        }
        Set<RedisNode> nodes = new HashSet<>();
        clusterNodes.forEach(address -> nodes.add(new RedisNode(address.split(":")[0].trim(), Integer.parseInt(address.split(":")[1]))));

        RedisClusterConfiguration clusterConfiguration = new RedisClusterConfiguration();
        clusterConfiguration.setClusterNodes(nodes);
        clusterConfiguration.setPassword(RedisPassword.of(redisProperties.getPassword()));
        clusterConfiguration.setMaxRedirects(redisProperties.getCluster().getMaxRedirects());

        LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(clusterConfiguration, clientConfig);
        lettuceConnectionFactory.setValidateConnection(validateConnection);
        lettuceConnectionFactory.setShareNativeConnection(setShareNativeConnection); //是否允许多个线程操作共用同一个缓存连接，默认true，false时每个操作都将开辟新的连接
        if(resetConnection){
            lettuceConnectionFactory.resetConnection(); // 重置底层共享连接, 在接下来的访问时初始化
        }
        return lettuceConnectionFactory;
    }

    @Bean("reactiveRedisTemplate")
    public ReactiveRedisTemplate<String, Object> objectReactiveRedisTemplate() {
        StringRedisSerializer stringSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer<Object> valueSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        valueSerializer.setObjectMapper(new ObjectMapper());

        RedisSerializationContext<String, Object> context = RedisSerializationContext.<String, Object>newSerializationContext()
                .key(stringSerializer)
                .value(valueSerializer)
                .hashKey(stringSerializer)
                .hashValue(valueSerializer)
                .build();
        return new ReactiveRedisTemplate<>(lettuceConnectionFactory(), context);
    }

    @Bean("stringReactiveRedisTemplate")
    public ReactiveRedisTemplate<String, String> stringReactiveRedisTemplate(ReactiveRedisConnectionFactory factory) {
        StringRedisSerializer stringSerializer = new StringRedisSerializer();
        RedisSerializationContext<String, String> context = RedisSerializationContext.<String, String>newSerializationContext()
                .key(stringSerializer)
                .value(stringSerializer)
                .hashKey(stringSerializer)
                .hashValue(stringSerializer)
                .build();
        return new ReactiveRedisTemplate<>(lettuceConnectionFactory(), context);
    }
}
